<template>
  <div class="link-page-container">
    <!-- 错误提示区域 -->
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    
    <!-- 加载提示 -->
    <div v-else-if="isLoading" class="loading-message">
      正在加载页面...
    </div>
    
    <!-- Iframe显示区域 -->
    <div v-else class="iframe-container">
      <iframe
        :src="targetUrl"
        frameborder="0"
        class="content-iframe"
        @load="onIframeLoad"
        @error="onIframeError"
      ></iframe>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';

export default defineComponent({
  name: 'LinkPage',
  setup() {
    // 响应式数据
    const targetUrl = ref('');
    const errorMessage = ref('');
    const isLoading = ref(true);

    // 从URL参数中获取目标URL
    const getUrlFromParams = () => {
      try {
        // 获取URL中的查询参数
        const queryParams = new URLSearchParams(window.location.search);
        
        // 获取'url'参数
        const urlParam = atob(queryParams.get('url'));
        
        if (!urlParam) {
          throw new Error('URL参数缺失，请在地址栏中添加?url=目标网址');
        }
        
        // 验证URL格式是否正确
        validateUrl(urlParam);
        
        // 设置目标URL
        targetUrl.value = urlParam;
         isLoading.value = false;
      } catch (error) {
        errorMessage.value = (error as Error).message;
        isLoading.value = false;
      }
    };
    
    // 验证URL格式
    const validateUrl = (url: string) => {
      try {
        // 尝试创建URL对象，如果失败会抛出异常
        new URL(url);
      } catch {
        // 如果URL没有协议，尝试添加http协议
        try {
          new URL('http://' + url);
        } catch {
          throw new Error('无效的URL格式');
        }
      }
    };
    
    // Iframe加载完成回调
    const onIframeLoad = () => {
      isLoading.value = false;
    };
    
    // Iframe加载错误回调
    const onIframeError = () => {
      errorMessage.value = '页面加载失败，请检查URL是否有效';
      isLoading.value = false;
    };

    // 组件挂载后获取URL参数中的路径
    onMounted(() => {
      getUrlFromParams();
    });

    return {
      targetUrl,
      errorMessage,
      isLoading,
      onIframeLoad,
      onIframeError
    };
  }
});
</script>

<style scoped>
.link-page-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.page-header {
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid #e8e8e8;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.error-message {
  padding: 20px;
  margin: 20px;
  background-color: #fff1f0;
  color: #f5222d;
  border: 1px solid #ffccc7;
  border-radius: 4px;
}

.loading-message {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 16px;
  color: #1890ff;
}

.iframe-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.content-iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style>